package com.angel.flieutils;

import com.angel.config.MyConfig;
import com.angel.exception.ErrorInfo;
import com.angel.exception.StatusException;
import com.angel.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/file")
public class UpLoad {
    @Autowired
    private MyConfig myConfig;

    /**
     * 单文件上传
     *
     * @param file
     * @return
     */
    @RequestMapping("/upload")
    @ResponseBody
    @ExceptionHandler(StatusException.class)
    public Object upLoadFile(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // 文件存放服务端的位置
                String abPath = pathIsExists(myConfig.getFileuploadpath(), "tmpFiles");
                String suffix=getFileSuffix(file);
                // 写文件到服务器
                File serverFile = new File(abPath + File.separator + TimeUtils.getTime() + "." + suffix);
                String imageUrl = File.separator+myConfig.getVitrPath()+File.separator+"tmpFiles"+ File.separator + TimeUtils.getTime() + "." + suffix;
                System.out.println(imageUrl);
                file.transferTo(serverFile);
                System.out.println(serverFile.getCanonicalPath()+"文件上传成功"+serverFile.getAbsolutePath());
                ErrorInfo<String> info =new ErrorInfo<>(ErrorInfo.OK,"文件上传成功");
                info.setData(imageUrl);
                return info;
            } catch (Exception e) {
                return new ErrorInfo<>(ErrorInfo.ERROR,"文件上传失败");
            }
        } else {
            return new ErrorInfo<>(ErrorInfo.ERROR,"请在检查你的文件");
        }
    }

    /**
     * 多文件上传
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploads")
    @ResponseBody
    @ExceptionHandler(StatusException.class)
    public Object batchUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        String abPath = pathIsExists(myConfig.getFileuploadpath(), "manyFiles");
        List<String> paths=new ArrayList<>();
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    String suffix =getFileSuffix(file);
                    File tmp =new File(abPath + File.separator + TimeUtils.getTime() + "." + suffix);
                    String imageUrl = File.separator+myConfig.getVitrPath()+File.separator+"manyFiles"+ File.separator + TimeUtils.getTime() + "." + suffix;
                    stream = new BufferedOutputStream(new FileOutputStream(tmp));
                    stream.write(bytes);
                    System.out.println(imageUrl);
                    System.out.println("-----"+tmp.getCanonicalPath());
                    paths.add(imageUrl);
                    stream.close();
                } catch (Exception e) {
                    return new ErrorInfo<>(ErrorInfo.ERROR,"文件上传失败");
                }
            } else {
                return new ErrorInfo<>(ErrorInfo.ERROR,"请在检查你的文件");
            }
        }
        System.out.println("文件上传完成");
        return new ErrorInfo<List>(ErrorInfo.OK,"文件上传成功",paths);
    }

    /***
     * 判断文件路径是否存在，不存在创建一个新的路径
     * @param basePath 基础路径
     * @param tmpPath 不同的文件子路径
     *  @return 文件的绝对路径
     */
     private String pathIsExists(String basePath, String tmpPath) {
        File dir = new File(basePath + File.separator + tmpPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir.getAbsolutePath();
    }

    /**
     * 获取文件后缀
     * @param file
     * @return 文件后缀
     */
    private String getFileSuffix(MultipartFile file){
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        return suffix;
    }


}
